<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Top 5 Products</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
</head>
<body>
<button onclick="loadChart()">Load Chart</button>
<br><br>
<div id="chart" style="width: 600px; height: 400px; display: none;"></div>

<script>
    function loadChart() {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "/hbase_echarts/HBaseServletAJAX", true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    var productData = JSON.parse(xhr.responseText);
                    console.log("productData:", productData);
                    if (!productData || productData.length === 0) {
                        console.error("No data available for the chart");
                        document.getElementById("chart").style.display = "none";
                        return;
                    }
                    document.getElementById("chart").style.display = "block";
                    var chart = echarts.init(document.getElementById("chart"));
                    var option = {
                        title: {text: 'Top 5 Products by Rating'},
                        xAxis: {
                            type: 'category', data: productData.map(function (item) {
                                return item.name;
                            })
                        },
                        yAxis: {type: 'value', name: 'Rating'},
                        series: [{
                            data: productData.map(function (item) {
                                return item.rating;
                            }),
                            type: 'bar',
                            itemStyle: {color: '#5470C6'}
                        }]
                    };
                    chart.setOption(option);
                } else {
                    console.error("Error loading chart, status: " + xhr.status + ", response: " + xhr.responseText);
                }
            }
        };
        xhr.send();
    }
</script>
</body>
</html>